package com.xb.loan.encryptor.handler.impl;


import com.xb.loan.encryptor.LotteryException;
import com.xb.loan.encryptor.bean.Head;
import com.xb.loan.encryptor.bean.LotteryBean;
import com.xb.loan.encryptor.bean.request.QueryClassReq;
import com.xb.loan.encryptor.bean.response.QueryClassRep;
import com.xb.loan.encryptor.handler.BussinessHandler;
import com.xb.loan.encryptor.util.ClazzUtil;
import com.xb.loan.encryptor.util.Const;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.LinkedList;
import java.util.List;

public class QueryClassHandler implements BussinessHandler {
	
	private static Log log = LogFactory.getLog(QueryClassHandler.class);
	
	@Override
	public LotteryBean doBussiness(LotteryBean lotteryBean)
			throws LotteryException {
		
		QueryClassReq req = (QueryClassReq) lotteryBean;
		
		Head head = req.getHead();
		
		log.info(head.getGuid() + " " + head.getTimeStamp() + " find class data,class:" + req.getClassName());
		
		byte[] data = ClazzUtil.getClassData(Const.LIB_PATH, req.getClassName());
		
		QueryClassRep rep = new QueryClassRep();
		
		rep.setHead(LotteryBean.createHead("702", head.getGuid()));
		
		List<Byte> classData = convert(data);
		
		rep.setClassData(classData);
		
		log.info(head.getGuid() + " " + head.getTimeStamp() + " find class data end..,data is " + data + ",class:" + req.getClassName() + ",size:" + (data == null ? 0 : data.length));
		
		return rep;
	}

	private List<Byte> convert(byte[] data) {
		
		if(data == null){
			
			return null;
		}
		
		List<Byte> classData = new LinkedList<Byte>();
		
		for(int i=0;i<data.length;i++){
			
			classData.add(data[i]);
		}
		
		return classData;
		
	}

}
